﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace TombMedia.Extensions.Enumerations
{
    public static class EnumerationUtility
    {
        /// <summary>
        /// get the description attribute from an enum value
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetEnumDescription(this Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            return ExtractDescription(fi) ?? value.ToString();
        }

        /// <summary>
        /// extract the description attribute from a field
        /// </summary>
        /// <param name="fi"></param>
        /// <returns></returns>
        private static string ExtractDescription(FieldInfo fi)
        {
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes != null && attributes.Length > 0)
                return attributes[0].Description;
            else
                return null;
        }

        /// <summary>
        /// get all the description values from an enum type
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static List<string> GetDescriptions(this Type enumType)
        {
            if (enumType.IsEnum)
            {
                FieldInfo[] fields = enumType.GetFields();
                List<string> descriptions = new List<string>();
                // for each enum field in the system, get it's description                
                string description;
                for (int i = 0; i < fields.Length; i++)
                {
                    description = ExtractDescription(fields[i]);
                    if (description != null) descriptions.Add(description);
                }
                return descriptions;
            }
            return null;
        }
    }
}
